import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  Card, 
  Spin, 
  Alert, 
  Button, 
  Row, 
  Col, 
  Table, 
  Tag, 
  Space, 
  Input,
  Select,
  Dropdown,
  Menu
} from 'antd';
import { 
  FaDatabase, 
  FaDownload,
  FaSearch,
  FaFilter,
  FaSync,
  FaEye,
  FaTrash,
  FaChartBar
} from 'react-icons/fa';
import { motion } from 'framer-motion';
import { useAuthStore } from '../../../stores/authStore';
import { useThemeStore } from '../../../stores/themeStore';
import { getTheme } from '../../../theme/config';
import CustomTable from '../../../components/custom/CustomTable';
import CustomCard from '../../../components/custom/CustomCard';
import type { ColumnsType } from 'antd/es/table';
import { notification } from '../../../components/common';

const { Option } = Select;

// 模拟数据类型
interface CrawlerData {
  id: string;
  name: string;
  project: string;
  spider: string;
  items_count: number;
  size: string;
  created_at: string;
  status: string;
}

const CrawlerDataPage: React.FC = () => {
  const navigate = useNavigate();
  const { isAuthenticated } = useAuthStore();
  const { mode } = useThemeStore();
  const theme = getTheme(mode);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [dataList, setDataList] = useState<CrawlerData[]>([]);
  const [searchText, setSearchText] = useState('');

  // 检查认证状态
  useEffect(() => {
    if (!isAuthenticated) {
      navigate('/login');
    }
  }, [isAuthenticated, navigate]);

  // 模拟获取数据列表
  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        setError(null);
        
        // 模拟数据
        const mockData: CrawlerData[] = [
          {
            id: '1',
            name: '电商商品数据_20231201',
            project: 'ecommerce_scraper',
            spider: 'product_spider',
            items_count: 12543,
            size: '45.2 MB',
            created_at: '2023-12-01 14:30:22',
            status: 'completed'
          },
          {
            id: '2',
            name: '新闻文章数据_20231201',
            project: 'news_scraper',
            spider: 'article_spider',
            items_count: 8765,
            size: '32.1 MB',
            created_at: '2023-12-01 12:15:45',
            status: 'completed'
          },
          {
            id: '3',
            name: '社交媒体数据_20231201',
            project: 'social_scraper',
            spider: 'post_spider',
            items_count: 23456,
            size: '87.5 MB',
            created_at: '2023-12-01 10:22:18',
            status: 'completed'
          },
          {
            id: '4',
            name: '招聘信息数据_20231130',
            project: 'job_scraper',
            spider: 'job_spider',
            items_count: 5678,
            size: '21.8 MB',
            created_at: '2023-11-30 16:45:33',
            status: 'completed'
          }
        ];
        
        setDataList(mockData);
      } catch (err) {
        console.error('获取数据失败:', err);
        setError('获取数据失败: ' + (err instanceof Error ? err.message : '未知错误'));
      } finally {
        setLoading(false);
      }
    };

    if (isAuthenticated) {
      fetchData();
    }
  }, []); // 空依赖数组确保只在组件挂载时执行一次

  // 刷新数据列表
  const refreshData = async () => {
    try {
      setLoading(true);
      // 模拟刷新
      await new Promise(resolve => setTimeout(resolve, 1000));
      notification.success({
        title: '刷新成功',
        message: '数据刷新成功'
      });
    } catch (err) {
      notification.error({
        title: '刷新失败',
        message: '刷新失败: ' + (err instanceof Error ? err.message : '未知错误')
      });
    } finally {
      setLoading(false);
    }
  };

  // 下载数据
  const downloadData = (id: string, format: string) => {
    notification.info({
      title: '下载数据',
      message: `下载数据 ${id} 为 ${format} 格式`
    });
    // 这里应该实现实际的下载逻辑
  };

  // 查看数据详情
  const viewDataDetails = (id: string) => {
    notification.info({
      title: '查看数据详情',
      message: `查看数据详情 ${id}`
    });
    // 这里应该跳转到数据详情页面
  };

  // 删除数据
  const deleteData = (id: string) => {
    notification.info({
      title: '删除数据',
      message: `删除数据 ${id}`
    });
    // 这里应该实现实际的删除逻辑
  };

  // 获取状态标签颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed': return 'success';
      case 'processing': return 'processing';
      case 'failed': return 'error';
      default: return 'default';
    }
  };

  // 表格列定义
  const columns: ColumnsType<CrawlerData> = [
    {
      title: '数据名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => (
        <span style={{ color: theme.textPrimary, fontWeight: 'bold' }}>{text}</span>
      )
    },
    {
      title: '项目',
      dataIndex: 'project',
      key: 'project'
    },
    {
      title: '爬虫',
      dataIndex: 'spider',
      key: 'spider'
    },
    {
      title: '数据量',
      dataIndex: 'items_count',
      key: 'items_count',
      render: (count: number) => (
        <span>{count.toLocaleString()}</span>
      )
    },
    {
      title: '大小',
      dataIndex: 'size',
      key: 'size'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={getStatusColor(status)}>{status}</Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at'
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="primary" 
            size="small"
            icon={<FaEye />}
            onClick={() => viewDataDetails(record.id)}
          >
            查看
          </Button>
          <Dropdown
            trigger={['click']}
            menu={{
              items: [
                {
                  key: 'json',
                  label: (
                    <span style={{ 
                      color: 'inherit',
                      transition: 'color 0.3s ease'
                    }}>
                      JSON格式
                    </span>
                  ),
                  onClick: () => downloadData(record.id, 'JSON')
                },
                {
                  key: 'csv',
                  label: (
                    <span style={{ 
                      color: 'inherit',
                      transition: 'color 0.3s ease'
                    }}>
                      CSV格式
                    </span>
                  ),
                  onClick: () => downloadData(record.id, 'CSV')
                },
                {
                  key: 'excel',
                  label: (
                    <span style={{ 
                      color: 'inherit',
                      transition: 'color 0.3s ease'
                    }}>
                      Excel格式
                    </span>
                  ),
                  onClick: () => downloadData(record.id, 'Excel')
                }
              ]
            }}
          >
            <Button 
              size="small"
              icon={<FaDownload />}
            >
              下载
            </Button>
          </Dropdown>
          <Button 
            danger 
            size="small"
            icon={<FaTrash />}
            onClick={() => deleteData(record.id)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ];

  // 获取卡片样式
  const getCardStyle = () => ({
    background: theme.cardBackground,
    border: `1px solid ${theme.cardBorder}`,
    borderRadius: '12px',
    boxShadow: mode === 'light' ? theme.cardShadow : 'none'
  });

  // 过滤数据
  const filteredData = dataList.filter(item => 
    item.name.toLowerCase().includes(searchText.toLowerCase()) ||
    item.project.toLowerCase().includes(searchText.toLowerCase()) ||
    item.spider.toLowerCase().includes(searchText.toLowerCase())
  );

  if (!isAuthenticated) {
    return null;
  }

  return (
    <div style={{ padding: '24px', color: theme.textPrimary }}>
      <motion.div
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
      >
        <div style={{ marginBottom: '24px' }}>
          <h1 style={{ 
            color: theme.glowColor, 
            fontSize: '28px',
            fontWeight: 'bold',
            marginBottom: '8px'
          }}>
            <FaDatabase style={{ marginRight: '12px' }} />
            爬虫数据管理
          </h1>
          <p style={{ 
            fontSize: '16px',
            opacity: 0.8,
            marginBottom: '24px',
            color: theme.textSecondary
          }}>
            查看、导出和管理爬取的数据
          </p>
        </div>

        {/* 操作栏 */}
        <div style={{ 
          marginBottom: '24px',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          flexWrap: 'wrap',
          gap: '12px'
        }}>
          <div>
            <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
              <Button 
                type="primary" 
                icon={<FaChartBar />}
                onClick={() => notification.info({
                  title: '功能待实现',
                  message: '数据分析功能待实现'
                })}
              >
                数据分析
              </Button>
            </motion.div>
            <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }} style={{ display: 'inline-block', marginLeft: '12px' }}>
              <Button 
                icon={<FaSync />}
                onClick={refreshData}
              >
                刷新
              </Button>
            </motion.div>
          </div>
          
          <div style={{ display: 'flex', gap: '12px' }}>
            <Input 
              placeholder="搜索数据..."
              prefix={<FaSearch style={{ color: theme.textSecondary }} />}
              style={{ width: '200px', background: theme.cardBackground, border: `1px solid ${theme.cardBorder}` }}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
            />
            <Select 
              placeholder="筛选项目"
              style={{ width: '150px', background: theme.cardBackground, border: `1px solid ${theme.cardBorder}` }}
              allowClear
            >
              <Option value="ecommerce_scraper">电商爬虫</Option>
              <Option value="news_scraper">新闻爬虫</Option>
              <Option value="social_scraper">社交媒体爬虫</Option>
            </Select>
            <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
              <Button icon={<FaFilter />}>
                筛选
              </Button>
            </motion.div>
          </div>
        </div>

        {/* 统计卡片 */}
        <Row gutter={[24, 24]} style={{ marginBottom: '24px' }}>
          <Col xs={24} sm={12} md={6}>
            <motion.div
              whileHover={{ y: -5 }}
              whileTap={{ scale: 0.98 }}
            >
              <Card 
                style={getCardStyle()}
                bodyStyle={{ padding: '20px' }}
              >
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <div style={{ 
                    background: `rgba(${mode === 'dark' ? '97, 220, 163' : '24, 144, 255'}, 0.15)`,
                    borderRadius: '50%',
                    width: '48px',
                    height: '48px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    marginRight: '16px'
                  }}>
                    <FaDatabase style={{ color: theme.glowColor, fontSize: '20px' }} />
                  </div>
                  <div>
                    <div style={{ 
                      fontSize: '14px', 
                      opacity: 0.8,
                      color: theme.textSecondary,
                      marginBottom: '4px'
                    }}>
                      总数据集
                    </div>
                    <div style={{ 
                      fontSize: '20px', 
                      fontWeight: 'bold', 
                      color: theme.glowColor 
                    }}>
                      {dataList.length}
                    </div>
                  </div>
                </div>
              </Card>
            </motion.div>
          </Col>

          <Col xs={24} sm={12} md={6}>
            <motion.div
              whileHover={{ y: -5 }}
              whileTap={{ scale: 0.98 }}
            >
              <Card 
                style={getCardStyle()}
                bodyStyle={{ padding: '20px' }}
              >
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <div style={{ 
                    background: `rgba(${mode === 'dark' ? '97, 220, 163' : '24, 144, 255'}, 0.15)`,
                    borderRadius: '50%',
                    width: '48px',
                    height: '48px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    marginRight: '16px'
                  }}>
                    <FaChartBar style={{ color: theme.glowColor, fontSize: '20px' }} />
                  </div>
                  <div>
                    <div style={{ 
                      fontSize: '14px', 
                      opacity: 0.8,
                      color: theme.textSecondary,
                      marginBottom: '4px'
                    }}>
                      总记录数
                    </div>
                    <div style={{ 
                      fontSize: '20px', 
                      fontWeight: 'bold', 
                      color: theme.glowColor 
                    }}>
                      {dataList.reduce((sum, item) => sum + item.items_count, 0).toLocaleString()}
                    </div>
                  </div>
                </div>
              </Card>
            </motion.div>
          </Col>

          <Col xs={24} sm={12} md={6}>
            <motion.div
              whileHover={{ y: -5 }}
              whileTap={{ scale: 0.98 }}
            >
              <Card 
                style={getCardStyle()}
                bodyStyle={{ padding: '20px' }}
              >
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <div style={{ 
                    background: `rgba(${mode === 'dark' ? '97, 220, 163' : '24, 144, 255'}, 0.15)`,
                    borderRadius: '50%',
                    width: '48px',
                    height: '48px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    marginRight: '16px'
                  }}>
                    <FaDownload style={{ color: theme.glowColor, fontSize: '20px' }} />
                  </div>
                  <div>
                    <div style={{ 
                      fontSize: '14px', 
                      opacity: 0.8,
                      color: theme.textSecondary,
                      marginBottom: '4px'
                    }}>
                      总大小
                    </div>
                    <div style={{ 
                      fontSize: '20px', 
                      fontWeight: 'bold', 
                      color: theme.glowColor 
                    }}>
                      186.6 MB
                    </div>
                  </div>
                </div>
              </Card>
            </motion.div>
          </Col>

          <Col xs={24} sm={12} md={6}>
            <motion.div
              whileHover={{ y: -5 }}
              whileTap={{ scale: 0.98 }}
            >
              <Card 
                style={getCardStyle()}
                bodyStyle={{ padding: '20px' }}
              >
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <div style={{ 
                    background: `rgba(${mode === 'dark' ? '97, 220, 163' : '24, 144, 255'}, 0.15)`,
                    borderRadius: '50%',
                    width: '48px',
                    height: '48px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    marginRight: '16px'
                  }}>
                    <FaDatabase style={{ color: theme.glowColor, fontSize: '20px' }} />
                  </div>
                  <div>
                    <div style={{ 
                      fontSize: '14px', 
                      opacity: 0.8,
                      color: theme.textSecondary,
                      marginBottom: '4px'
                    }}>
                      项目数
                    </div>
                    <div style={{ 
                      fontSize: '20px', 
                      fontWeight: 'bold', 
                      color: theme.glowColor 
                    }}>
                      4
                    </div>
                  </div>
                </div>
              </Card>
            </motion.div>
          </Col>
        </Row>

        {/* 数据列表 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.2 }}
        >
          <CustomCard>
            {error ? (
              <Alert
                message="错误"
                description={error}
                type="error"
                showIcon
                style={{ marginBottom: '16px' }}
              />
            ) : null}
            
            {loading ? (
              <div style={{ textAlign: 'center', padding: '40px' }}>
                <Spin size="large" tip="加载中..." />
              </div>
            ) : (
              <CustomTable 
                dataSource={filteredData}
                columns={columns}
                rowKey="id"
                pagination={{
                  pageSize: 10,
                  showSizeChanger: true,
                  showQuickJumper: true
                }}
                locale={{
                  emptyText: (
                    <div style={{ padding: '40px', textAlign: 'center', color: theme.textSecondary }}>
                      <FaDatabase style={{ fontSize: '48px', marginBottom: '16px', opacity: 0.5, color: theme.glowColor }} />
                      <p>暂无爬虫数据</p>
                      <p style={{ fontSize: '14px' }}>
                        等待爬虫任务完成后将显示数据
                      </p>
                    </div>
                  )
                }}
              />
            )}
          </CustomCard>
        </motion.div>
      </motion.div>
    </div>
  );
};

export default CrawlerDataPage;